<?php


namespace App\Http\Controllers\Api\Repositories;


use App\Models\Posts\WxCollect;
use App\Models\Posts\WxLike;
use App\Models\Posts\WxPost;
use App\Models\Posts\WxPost as Model;
use App\Models\Posts\WxPostsAddress;
use App\Models\Posts\WxPostsImg;
use App\Models\Posts\WxPostsTag;
use App\Models\Posts\WxPostsVideo;
use App\Models\Posts\WxTag;
use App\Models\WxCircle;
use App\Models\WxExceptional;
use App\Models\WxNotice;
use App\Models\WxNotice as NoticeModel;
use App\Models\WxPostsGoods;
use App\Models\WxShopGoods;
use App\Models\WxUser;
use App\Models\WxUserFollow;
use Illuminate\Support\Facades\DB;
use App\Dengje\Utils\Settings;

class PostsRepositores
{
    /**
     * Model.
     *
     * @var string
     */
    protected $eloquentClass = Model::class;

    /**
     * 新增帖子
     * posts_content 帖子内容
     * user_id 用户id
     * circle_id 圈子id
     * circle_name 圈子名称
     * address_name 地址名称
     * address_detailed 详细地址
     * latitude 经度
     * longitude 维度
     * address_id 地址ID
     * tags_ids 标签id
     * image_urls 图片
     * video_url 视频
     *
     *
     * @param $data
     */
    public static function add($uid, $contents, $circle_id, $tags, $goods, $images, $video, $address, $videoThumbUrl, $video_width, $video_height)
    {


        DB::beginTransaction();
        try {

            if (!empty($address)) {


                // 创建地址
                $addr = new WxPostsAddress([
                    'address_name' => $address['address_name'],
                    'address_detailed' => $address['address_detailed'],
                    'latitude' => $address['latitude'],
                    'longitude' => $address['longitude']
                ]);
                $addr->save();
                $addressId = $addr->id;
            }


            // 圈子名称
            $circle = WxCircle::where('id', $circle_id)->first();
            // 判断是否需要审核帖子
            if (Settings::get('is_audit_posts') == 1) {
                $posts_state = 1;
            } else {
                $posts_state = 0;
            }

            // 创建帖子
            $post = new Model([
                'posts_content' => $contents,
                'user_id' => $uid,
                'circle_id' => $circle_id,
                'circle_name' => $circle['circle_name'],
                'address_id' => empty($addressId) ? 0 : $addressId,
                'tags_id' => 0
            ]);
            $post->is_examine = $posts_state;
            $post->save();
            $postId = $post->id;


            // 图片组
            if (!empty($images)) {
                $postImage = [];
                foreach ($images as $k => $v) {
                    $postImage[$k]['posts_id'] = $postId;
                    $postImage[$k]['user_id'] = $uid;
                    $postImage[$k]['img_url'] = $v['url'];
                }
                $postImg = new WxPostsImg();
                $postImg->addAll($postImage);
            }

            // 标签
            if (!empty($tags)) {
                $postTag = [];
                $tagsIds = [];
                foreach ($tags as $k => $v) {
                    $postTag[$k]['posts_id'] = $postId;
                    $postTag[$k]['tags_id'] = $v['id'];
                    $tagsIds[] = $v['id'];
                }
                $tags = new WxPostsTag();
                $tags->addAll($postTag);
                WxTag::whereIn('id', $tagsIds)->increment('tags_number');
            }

            // 商品
            if (!empty($goods)) {
                $postGoods = [];
                foreach ($goods as $k => $v) {
                    $postGoods[$k]['posts_id'] = $postId;
                    $postGoods[$k]['goods_id'] = $v['id'];
                }
                $goods = new WxPostsGoods();
                $goods->addAll($postGoods);
            }


            // 视频组
            if (!empty($video)) {
                $postVideoModel = new WxPostsVideo();
                $postVideoModel->user_id = $uid;
                $postVideoModel->posts_id = $postId;
                $postVideoModel->video_url = $video;
                $postVideoModel->video_thumb_url = $videoThumbUrl;
                $postVideoModel->video_width = $video_width;
                $postVideoModel->video_height = $video_height;
                $postVideoModel->save();
            }

            //给对应圈子圈主发送待审核信息
            $noticeModel = new WxNotice();
            $noticeModel->user_id = $circle['user_id'];
            $noticeModel->posts_id = $postId;
            $noticeModel->title = '有新的内容待审核';
            $noticeModel->content = '您创建的圈子「' . $circle['circle_name'] . '」有一篇新的内容等待您去审核哦，请务必在24小时内进行处理。';
            $noticeModel->is_read = 0;
            $noticeModel->notice_type = 7;
            $noticeModel->save();

            DB::commit();

            return true;
        } catch (\Exception $e) {
            DB::rollBack();
//
            return $e->getMessage();
        }


    }

    /**
     * 推荐的帖子列表
     * @param $uid
     * @param int $limit
     * @return mixed
     */
    public static function list($uid, $limit = 10)
    {


        $data = (new Model())
            ->where('is_examine', 1)
            ->where('posts_state', 0)
            ->orderBy('is_sticky', 'desc')
            ->orderBy('id', 'desc')
            ->simplePaginate($limit);

        $data = self::postsParame($data, $uid);//文章详情

        return $data;
    }

    /**
     * 我关注的帖子列表
     * @param $uid
     * @param int $limit
     * @return mixed
     */
    public static function followPosts($uid, $limit = 10)
    {
        $userFollowIds = WxUserFollow::where('user_id', $uid)->pluck('user_follow_id');

        $data = (new Model())
            ->where('is_examine', 1)
            ->where('posts_state', 0)
            ->whereIn('user_id', $userFollowIds)
            ->orderBy('id', 'desc')
            ->simplePaginate($limit);

        $data = self::postsParame($data, $uid);//文章详情

        return $data;
    }


    /**
     * 热榜的帖子列表
     * @param $uid
     * @param int $limit
     * @return mixed
     */
    public static function hotPosts($uid, $limit = 10)
    {


        $data = (new Model())
            ->where('is_examine', 1)
            ->where('posts_state', 0)
            ->withCount('like as like_count')
            ->orderBy('like_count', 'desc')
            ->simplePaginate($limit);

        $data = self::postsParame($data, $uid);//文章详情

        return $data;
    }


    /**
     * 板块推荐的帖子列表
     * @param $uid
     * @param int $limit
     * @return mixed
     */
    public static function getListByPlate($uid, $plate_id, $limit = 6)
    {

        $circleIds = WxCircle::where('plate_id', $plate_id)->pluck('id');

        $data = (new Model())
            ->where('is_examine', 1)
            ->where('posts_state', 0)
            ->whereIn('circle_id', $circleIds)
            ->orderBy('id', 'desc')
            ->simplePaginate($limit);

        $data = self::postsParame($data, $uid);//文章详情

        return $data;
    }


    /**
     * 精选文章
     */
    public static function choiceness()
    {
        $data = WxPost::where('is_examine', 1)
            ->where('is_information', 1)
            ->where('posts_state', 0)
            ->orderBy('id', 'desc')
            ->limit(6)
            ->get(['id', 'posts_content']);

        return $data->append('imagea');
    }


    /**
     * 点赞
     */
    public static function addLike($uid, $posts_id)
    {

        $posts_user_id = WxPost::where('id', $posts_id)->pluck('user_id')->first();
        $isExists = WxLike::where('posts_user_id', $posts_user_id)
            ->where('posts_id', $posts_id)
            ->where('user_id', $uid)
            ->exists();
        if (!$isExists) {
            // 点赞
            $wxLike = new WxLike();
            $wxLike->posts_user_id = $posts_user_id;
            $wxLike->posts_id = $posts_id;
            $wxLike->user_id = $uid;
            $wxLike->save();

            $user = WxUser::where('id', $uid)->first('user_name');

            $noticeModel = new NoticeModel;
            $noticeModel->user_id = $posts_user_id;
            $noticeModel->posts_id = $posts_id;
            $noticeModel->title = '收到了一个喜欢';
            $noticeModel->content = '您的动态收到了「' . $user['user_name'] . '」的喜欢。';
            $noticeModel->is_read = 0;
            $noticeModel->notice_type = 2;
            $noticeModel->save();


        } else {
            // 取消点赞
            (new WxLike())->where('posts_user_id', $posts_user_id)
                ->where('posts_id', $posts_id)
                ->where('user_id', $uid)
                ->delete();

            (new WxNotice())->where('posts_id', $posts_id)
                ->where('user_id', $posts_user_id)
                ->where('notice_type', 2)
                ->delete();
        }

    }


    /**
     * 收藏
     */
    public static function addCollect($uid, $posts_id)
    {

        $posts_user_id = WxPost::where('id', $posts_id)->pluck('user_id')->first();
        $isExists = WxCollect::where('posts_user_id', $posts_user_id)
            ->where('posts_id', $posts_id)
            ->where('user_id', $uid)
            ->exists();
        if (!$isExists) {
            // 收藏
            $wxLike = new WxCollect();
            $wxLike->posts_user_id = $posts_user_id;
            $wxLike->posts_id = $posts_id;
            $wxLike->user_id = $uid;
            $wxLike->save();

            $user = WxUser::where('id', $uid)->first('user_name');

            $noticeModel = new NoticeModel;
            $noticeModel->user_id = $posts_user_id;
            $noticeModel->posts_id = $posts_id;
            $noticeModel->title = '收到了一个收藏';
            $noticeModel->content = '您的动态被「' . $user['user_name'] . '」收藏啦！';
            $noticeModel->is_read = 0;
            $noticeModel->notice_type = 3;
            $noticeModel->save();

        } else {
            // 取消收藏
            (new WxCollect())->where('posts_user_id', $posts_user_id)
                ->where('posts_id', $posts_id)
                ->where('user_id', $uid)
                ->delete();


            (new WxNotice())->where('posts_id', $posts_id)
                ->where('user_id', $posts_user_id)
                ->where('notice_type', 3)
                ->delete();
        }

    }

    /**
     * 关注
     * @param $uid
     * @param $user_follow_id
     */
    public static function followUser($uid, $user_follow_id)
    {

        $isExists = WxUserFollow::where('user_follow_id', $user_follow_id)
            ->where('user_id', $uid)
            ->exists();
        if (!$isExists) {

            // 不能关注自己
            if ($user_follow_id != $uid) {
                // 关注
                $wxLike = new WxUserFollow();
                $wxLike->user_follow_id = $user_follow_id;
                $wxLike->user_id = $uid;
                $wxLike->save();
            }


        } else {
            // 取消关注
            (new WxUserFollow())->where('user_follow_id', $user_follow_id)
                ->where('user_id', $uid)
                ->delete();
        }
    }

    /**
     * 删除帖子
     */

    public static function deletePosts($posts_id)
    {
        DB::beginTransaction();
        try {
            // 删除文章(真删)
//            $addressId = WxPost::where('id', $posts_id)->pluck('address_id')->first();
//            WxPost::destroy($posts_id);
//            WxPostsAddress::where('id', $addressId)->delete();
//            WxPostsImg::where('posts_id', $posts_id)->delete();
//            WxPostsVideo::where('posts_id', $posts_id)->delete();
//            WxPostsTag::where('posts_id', $posts_id)->delete();
            // 删除文章(假删)
            WxPost::where('id', $posts_id)->update(['posts_state' => 1]);
            Db::commit();
        } catch (\Exception $e) {
            DB::rollBack();
//
            return $e->getMessage();
        }
    }

    /**
     * 获取文章详情
     * @param $uid
     * @param $posts_id
     * @return mixed
     */
    public static function postsDetail($uid, $posts_id)
    {

        $data = (new Model())
            ->where('id', $posts_id)
            ->get();

        $data = self::postsParame($data, $uid);//文章详情

        return $data;
    }


    /**
     * 0:我发布的，1: 我收藏的；2:我喜欢的 3:我打赏的
     * @param $uid
     * @param int $limit
     * @return mixed
     */
    public static function myPosts($uid, $limit = 10, $type = 0)
    {

        if ($type == 0) {
            return self::mySendPosts($uid, $limit);
        } elseif ($type == 1) {
            return self::myCollectPosts($uid, $limit);
        } elseif ($type == 2) {
            return self::myLikePosts($uid, $limit);
        } elseif ($type == 3) {
            return self::myExceptionalPosts($uid, $limit);
        }
    }

    /**
     * 我发的帖子
     * @return mixed
     */
    public static function mySendPosts($uid, $limit = 10)
    {
        $query = (new Model())
            ->withCount('like as like_count');
        if (Settings::get('is_user_center_show_posts') == 1) {
            $query->where('is_examine', 1);
        }
        $query->where('user_id', $uid)
            ->whereIn('posts_state', [0, 2])
            ->orderBy('id', 'desc');
        $data = $query->paginate($limit);

        $data = self::postsParame($data, $uid);//文章详情

        return $data;
    }

    /**
     * 我收藏的文章列表
     * @param $uid
     * @param int $limit
     * @return mixed
     */
    public static function myCollectPosts($uid, $limit = 10)
    {
        $postsIds = WxCollect::where('user_id', $uid)->pluck('posts_id');
        $data = (new Model())
            ->where('is_examine', 1)
            ->where('posts_state', 0)
            ->whereIn('id', $postsIds)
            ->orderBy('id', 'desc')
            ->paginate($limit);

        $data = self::postsParame($data, $uid);//文章详情

        return $data;
    }


    /**
     * 我喜欢的
     * @return mixed
     */
    public static function myLikePosts($uid, $limit = 10)
    {
        $postsIds = WxLike::where('user_id', $uid)->pluck('posts_id');
        $data = (new Model())
            ->where('is_examine', 1)
            ->where('posts_state', 0)
            ->whereIn('id', $postsIds)
            ->paginate($limit);

        $data = self::postsParame($data, $uid);//文章详情

        return $data;
    }

    /**
     * 我打赏的
     * @return mixed
     */
    public static function myExceptionalPosts($uid, $limit = 10)
    {
        $postsIds = WxExceptional::where('user_id', $uid)->pluck('posts_id');
        $data = (new Model())
            ->where('is_examine', 1)
            ->where('posts_state', 0)
            ->whereIn('id', $postsIds)
            ->paginate($limit);

        $data = self::postsParame($data, $uid);//文章详情

        return $data;
    }


    /**
     * 根据圈子ID获取最新和最热的帖子
     * @param $circle_id
     * @param $type 0:最新，1：最热
     */
    public static function postsByCircleId($circle_id, $type, $limit, $uid)
    {
        // 最新
        if ($type == 0) {
            $data = (new Model())
                ->where('is_examine', 1)
                ->where('posts_state', 0)
                ->where('circle_id', $circle_id)
                ->orderBy('id', 'desc')
                ->simplePaginate($limit);

            $data = self::postsParame($data, $uid);//文章详情

            return $data;
        } elseif ($type == 1) {
            // 最热
            $data = (new Model())
                ->where('is_examine', 1)
                ->where('posts_state', 0)
                ->where('circle_id', $circle_id)
                ->withCount('like as like_count')
                ->orderBy('like_count', 'desc')
                ->simplePaginate($limit);

            $data = self::postsParame($data, $uid);//文章详情

            return $data;
        } elseif ($type == 2) {
            // 审核中的帖子
            $data = (new Model())
                ->where('is_examine', 0)
                ->where('circle_id', $circle_id)
                ->orderBy('id', 'desc')
                ->simplePaginate($limit);

            $data = self::postsParame($data, $uid);//文章详情

            return $data;
        }

    }

    /**
     * 搜索
     * @param $keyword
     * @param int $uid
     * @param int $limit
     * @return mixed
     */
    public static function searchPosts($keyword, $uid = 0, $limit = 10)
    {
        WxSearchRepositores::record($uid, $keyword);
        $data = (new Model())
            ->where('is_examine', 1)
            ->where('posts_state', 0)
            ->where('posts_content', 'like', '%' . $keyword . '%')
            ->simplePaginate($limit);

        $data = self::postsParame($data, $uid);//文章详情

        return $data;
    }

    /**
     * 商品晒单
     * @return mixed
     */
    public static function goodsBaskPosts($uid, $gid)
    {

        $postsIds = WxPostsGoods::where('goods_id', $gid)->pluck('posts_id');//帖子ID列表

        $data = (new Model())
            ->where('is_examine', 1)
            ->where('posts_state', 0)
            ->whereIn('id', $postsIds)
            ->paginate(6);

        $data = self::postsParame($data, $uid);//文章详情

        return $data;
    }


    public static function postsParame($data, $uid)
    {

        $data->map(function ($v) use ($uid) {
            $v->user = WxUser::where('id', $v->user_id)
                ->first(['user_avatar', 'user_name', 'id', 'is_member', 'is_official', 'is_authentication', 'gender']);//发帖人
            $v->images = WxPostsImg::where('posts_id', $v->id)->get(['img_url', 'posts_id']);//图片
            $v->video = WxPostsVideo::where('posts_id', $v->id)->first();//视频
            $v->address = WxPostsAddress::where('id', $v->address_id)->first();//地址
            $v->circle = WxCircle::where('id', $v->circle_id)->first(['id', 'circle_name']);//圈子
            $v->like_count = self::likeCont($v->id); // 帖子喜欢数量
            $v->is_my_posts = Model::isMyPosts($uid, $v->id); // 是否是我的帖子
            $v->is_follow_user = Model::isFollowUser($uid, $v->user_id);// 是否关注该用户
            $v->is_like = Model::isLike($uid, $v->id); // 是否喜欢
            $v->is_collect = Model::isCollec($uid, $v->id); // 是否收藏
            $tagsIds = WxPostsTag::where('posts_id', $v->id)->pluck('tags_id');//标签ID列表
            $v->tags = WxTag::whereIn('id', $tagsIds)->get(['tags_name', 'id']);//标签列表
            $goodsIds = WxPostsGoods::where('posts_id', $v->id)->pluck('goods_id');//商品ID列表
            $v->goods = WxShopGoods::whereIn('id', $goodsIds)->get(['id', 'pic', 'name', 'intro']);//商品列表
            $v->comment = (new Model())
                ->getComment($v->id, ['user_name', 'comment_content', 'user_id', 'posts_user_id', 'comment_img_url']); // 评论
            $v->comment_count = WxCommentRepositores::commentCount($v->id);//评论数量
            $v->exceptional_count = self::exceptionalCont($v->id); // 打赏总数
            $v->exceptional = self::exceptionalList($v->id);//获取帖子打赏列表
        });

        $data->append(['format_time', 'is_ellipsis', 'is_content_beyond']);

        return $data;

    }

    /**
     * 获取帖子喜欢数量
     */
    public static function likeCont($postId)
    {
        return WxLike::where(['posts_id' => $postId])->count();
    }

    /**
     * 获取帖子打赏总数
     */
    public static function exceptionalCont($postId)
    {
        return count(WxExceptional::where(['posts_id' => $postId])->groupBy('user_id')->get('id'));
    }

    /**
     * 获取帖子打赏列表(只显示头像)
     */
    public static function exceptionalList($postId)
    {


        $ids = WxExceptional::where('posts_id', $postId)
            ->groupBy('user_id')
            ->pluck('user_id');//打赏用户ID列表

        $data = WxUser::whereIn('id', $ids)->limit(6)->get(['user_avatar']);

        return $data;

    }
}
